//
//  WeddingDream.m
//  MMLOOK
//
//  Created by dllo on 15/8/24.
//  Copyright (c) 2015年 武俊娥. All rights reserved.
//

#import "WeddingDream.h"
#import "HMSegmentedControl.h" // 滑动栏的第三方
#import "AsynConnect.h"
#import "WedModel.h"
#import "MBProgressHUD.h"


#import "WedDreamCollectionViewCell.h" // collectionViewCell

#import "WedDetailViewController.h"
#import "SaveTools.h"
#import "JudgeConnection.h"
#import "PlayCollectionViewCell.h"

@interface WeddingDream ()<UICollectionViewDataSource, UICollectionViewDelegate,UIScrollViewDelegate,WedDreamCollectionViewCellDelegate>

@property (nonatomic, retain)HMSegmentedControl *segmentedControl;

@property (nonatomic, retain)UICollectionView *collection;
@property(nonatomic, retain)MBProgressHUD *mbProView;


@property(nonatomic, retain)NSMutableArray *urlArr;
@property (nonatomic, retain) NSMutableArray *collArray;



@end

@implementation WeddingDream

- (void)dealloc
{
    
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       
        
        self.urlArr = [NSMutableArray array];
        
        self.collArray = [NSMutableArray array];
        
        for (int i = 0; i < 7; i++) {
            
            //7个网址
            NSString *str = [NSString stringWithFormat:@"http://www.hunliji.com/products.json?page=1&category=%d&sort=0", i + 1];
            [self.urlArr addObject:str];
            
            //7个数组
            NSMutableArray *array = [NSMutableArray array];
            [_collArray addObject:array];
        }
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:253 / 255.0 green:180/255.0 blue:83/255.0 alpha:1];
    
    self.navigationItem.title = @"新娘必备";
    
    //创建滑动栏
    [self creatTopSegmentedControl];
    
    //创建collect
    [self creatCollection];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    
    self.tabBarController.tabBar.translucent = NO;
}


#pragma mark - 滑动栏
- (void)creatTopSegmentedControl
{
    self.segmentedControl = [[[HMSegmentedControl alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40 * OffHeight)] autorelease];
    
    self.segmentedControl.sectionTitles = @[@"婚纱", @"礼服", @"婚鞋", @"配饰", @"首饰", @"婚庆", @"家居",@"时尚"];
    
    //原来的颜色
    self.segmentedControl.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor grayColor]};
    self.segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 20, 0, 20);
    // 选中字的颜色
    self.segmentedControl.selectedTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor orangeColor]};
    //默认选中第一个
    self.segmentedControl.selectedSegmentIndex = 0;
    // 设置样式
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    //下划线所在位置
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    self.segmentedControl.selectionIndicatorColor = [UIColor orangeColor];
    
    
#pragma marks - segmentedControl 的点击
    
    [self.segmentedControl setIndexChangeBlock:^(NSInteger index) {
       
        [self.collection setContentOffset:CGPointMake(index * self.view.frame.size.width, 0) animated:YES];
        
    }];
    
    [self.view addSubview:self.segmentedControl];
    
}

#pragma mark - 创建collectionView
-(void)creatCollection
{

    UICollectionViewFlowLayout *layout = [[[UICollectionViewFlowLayout alloc] init] autorelease];
    
    layout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 64 - 40 * OffHeight -49);
    
    layout.minimumInteritemSpacing = 0;
    
    layout.minimumLineSpacing= 0;

    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40 * OffHeight, self.view.frame.size.width, self.view.frame.size.height - 64 - 40 * OffHeight -49) collectionViewLayout:layout];
    
    self.collection.backgroundColor = [UIColor orangeColor];
    
    self.collection.showsHorizontalScrollIndicator = NO;
    
    _collection.dataSource = self;
    _collection.delegate = self;
    
    _collection.pagingEnabled = YES;
    _collection.backgroundColor = [UIColor whiteColor];
    
    //cell注册
    
    for (int i = 0; i < self.collArray.count; i++) {
        
    [_collection registerClass:[WedDreamCollectionViewCell class] forCellWithReuseIdentifier:[NSString stringWithFormat:@"cell%d",i]];
        
    }
    
    
   
    [self.collection registerClass:[PlayCollectionViewCell class] forCellWithReuseIdentifier:@"play"];
    
    
    [self.view addSubview:self.collection];
    
    [_collection release];
    
}


#pragma mark - UISCrollView 滑动

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat pageWith = _collection.frame.size.width;
    NSInteger page = _collection.contentOffset.x / pageWith;
    [self.segmentedControl setSelectedSegmentIndex:page animated:YES];
    
}


#pragma mark - collectionView的协议方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return  [_collArray count] + 1;
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    
    if (indexPath.item < 7) {
        
   
    
    WedDreamCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[NSString stringWithFormat:@"cell%ld",indexPath.item] forIndexPath:indexPath];
    
       cell.count = indexPath.item;
    
       cell.delegate = self;
    
       cell.collectArray = [NSMutableArray arrayWithArray:[self.collArray objectAtIndex:indexPath.item]];
    
    //消息界面
    [cell pushDetailWithSendIdBlock:^(WedModel *model) {
        WedDetailViewController *wed = [[WedDetailViewController alloc]init];
        
        wed.model = model;
        
        [self.navigationController pushViewController:wed animated:YES];
        
        [wed release];

        
    }];
       return cell;
        
    } else {
        
        
    PlayCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"play" forIndexPath:indexPath];
        
        cell.root = self;
        
      return cell;
      
    }
    
    
    
}



-(void)readLocal:(WedDreamCollectionViewCell *)cell
{
    
    NSMutableArray *array = [self.collArray objectAtIndex:cell.count];
    
    [array removeAllObjects];
    
    NSString *urlStr = [self.urlArr objectAtIndex:cell.count];
    
    NSData *data = [SaveTools readDataWithName:[urlStr hash] directory:NSLibraryDirectory];
    
    if (data != nil) {
        
        [array addObjectsFromArray:[self handleData:data]];
        
        cell.collectArray = [NSMutableArray arrayWithArray:array];
        
        
    }

    
}


-(NSMutableArray *)handleData:(NSData *)data
{
    
    NSMutableArray *array = [NSMutableArray array];
    
    NSMutableDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    NSMutableArray *arr = [resultDic objectForKey:@"products"];
    
    for (NSMutableDictionary *dic in arr) {
        
        WedModel *model = [[WedModel alloc]initWithDic:dic];
        
        [array addObject:model];
        
        [model release];
    }

    return array;
}



#pragma mark -
#pragma mark 网络请求
- (void)beginRefresh:(WedDreamCollectionViewCell *)cell;
{
    
    // 添加加载动画
    MBProgressHUD *mbProView = [[[MBProgressHUD alloc] initWithView:cell] autorelease];
    mbProView.mode = MBProgressHUDModeIndeterminate;// 样式 菊花
    mbProView.labelText = @"(｢･ω･)｢ 加载中";
    [mbProView show:YES];
    [cell addSubview:mbProView];
    
    //有网才走下面的请求
    if ([JudgeConnection judgeConnection]) {
        
        cell.flag = YES;
        
        
        NSString *urlStr = [self.urlArr objectAtIndex:cell.count];
        
        if (cell.pageCount > 1) {
            
          urlStr = [urlStr stringByReplacingOccurrencesOfString:@"page=1" withString:[NSString stringWithFormat:@"page=%ld",cell.pageCount]];
            
        }
        
     
   //网络请求
    [AsynConnect asynConnectWithUrlstr:urlStr parmater:nil block:^(NSData *data) {
        
        [mbProView hide:YES];
        
        if (data != nil) {

            //写本地缓存
            if ([SaveTools saveDataWithName:[urlStr hash] directory:NSLibraryDirectory data:data]) {
                NSLog(@"存入本地啦");
            }
            
            NSMutableArray *array = [self.collArray objectAtIndex:cell.count];
            
            
            if (cell.pageCount == 1) {
                
                [array removeAllObjects];
                
            }
            
            //处理数据
            [array addObjectsFromArray:[self handleData:data]];
            
            cell.collectArray = [NSMutableArray arrayWithArray:array];
        }
        
    }];
        
} else {
        
        [mbProView hide:YES];
    }

}



@end
